package com.zj.whichone;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.zj.whichone.bean.IndexVo;
import com.zj.whichone.bean.ReturnInfo;
import com.zj.whichone.bean.User;
import com.zj.whichone.constant.Default;
import com.zj.whichone.constant.ReturnCode;
import com.zj.whichone.service.LoginService;

import cn.hn.java.summer.exception.BusinessException;
import cn.hn.java.summer.exception.MessageCodeException;
import cn.hn.java.summer.mvc.WebContext;

/**
 * Created by xw2sy on 2017-04-16.
 */
@Controller
@RequestMapping("/")
public class MainController extends BaseController{
	@Autowired
	LoginService loginService;
	@RequestMapping("/regeist")
	public ReturnInfo regeist(User user) throws MessageCodeException{
		System.out.println(user);
		ReturnInfo rinfo = loginService.regeist(user);
		if(rinfo.getCode()==0){
			addSessionAttribute(Default.USER_SESSION_KEY,user);
		}
		return rinfo;
	}
    @RequestMapping("/index")
    public IndexVo index() throws BusinessException{
    	User user=WebContext.getSessionCookie(Default.USER_SESSION_KEY,User.class);
    	System.out.println("come in "+user);
    	return loginService.index(user);
    }

    @RequestMapping(value = "/test/*",name = "/test")
    public void test(){
    }

    @RequestMapping(value = "login",method=RequestMethod.GET)
    public void getLogin(User user){
    	System.out.println(user);
    }
    @RequestMapping(value = "login",method=RequestMethod.POST)
    public ReturnInfo login(User user,RedirectAttributes attr){
    	user = loginService.login(user);
    	ReturnInfo rinfo = new ReturnInfo();
    	if(user == null){
    		rinfo.setCode(ReturnCode.LOGIN_FAIL);
    		rinfo.setMsg("用户名或密码错误");
    		return rinfo;
    	}
		addSessionAttribute(Default.USER_SESSION_KEY,user);
		rinfo.setMsg("用户登录成功");
		return rinfo;
    }

    /**
	 * 退出登录
	 */
	@RequestMapping("/logout")
	public void logout(){
		clearSession();
		redirectTo("/login.html");
	}
}
